<?php
/**
 * User: i@fedax.cn
 * Time: 2018/7/26 14:33
 */

namespace app\admin\model;

use think\Db;

class Withdrawal extends DataBase
{
    protected $name = 'withdrawal_apply';
    protected $autoWriteTimestamp = true;
    protected $createTime = 'created_at';
    protected $updateTime = 'updated_at';

    /*
     * 获取器，对输出数据进行自动处理
     */
    public function getStatusAttr($value){
        $status = ['1' => '申请中', '2' => '拒绝', '3' => '已通过'];
        return $status[$value];
    }
    public function getTypeAttr($value){
        $type = ['1'=>'礼物收益','2'=>'推荐收益'];
        return $type[$value];
    }
    /**
     * @param $page_config
     * @param $where
     * @param $order
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function getDataList(){
        $map = [
            'u_id' => 'user_id'
        ];
        $page_config = array(
            'page' => input('get.pageNum', 1),
            'list_rows' => input('get.limit', 10),
        );
        $order =  ['created_at'=>'desc'];
        $where = [];
        if(input('get.status')){ //  '1申请 2拒绝 3通过'
            $where[] = ['status','=',input('get.status')];
        }
        if (input('get.u_id')) {

//            $user_id = User::where('u_id','=',input('get.u_id'))->value('id');
//            $where[] = ['user_id', '=', $user_id];
              $where[] = [$map['u_id'],'=',input('get.u_id')];;
        }
        if(input('get.apply_type')){
            $where[] = ['type','=',input('get.apply_type')];
        }
        $startTime = input('get.start_time');
        $endTime = input('get.end_time');
        if(!empty($startTime) && !empty($endTime)){
            $startTime = strtotime($startTime);
            $endTime = strtotime($endTime);
            if($startTime <= $endTime)
                $where[] = ['created_at','between',[$startTime,$endTime]];
            else
                $where[] = ['created_at','between',[$endTime,$startTime]];
        }
        else if(!empty($startTime)){
            $startTime = strtotime($startTime);
            $where[] = ['created_at','>=',$startTime];
        }
        else if(!empty($endTime)){
            $endTime = strtotime($endTime);
            $where[] = ['created_at','<=',$endTime];
        }
        if(input('get.cheques')){
            $where[] = ['cheques','=',input('get.cheques')];
        }
        //被优化的部分，避免多表联查
//        return $this
//            ->view('Users', 'u_id')
//            ->view('WithdrawalInfo', 'alipay_card,alipay_name,phone,identity_card,submit_time', 'WithdrawalInfo.user_id=Users.id')
//            ->view('WithdrawalApply', 'id,apply_amount,remark,status,type,create_time,user_id', 'WithdrawalApply.user_id=Users.id')
//            ->where($where)
//            ->order($order)
//            ->paginate($page_config);

        $data = $this->where($where)->order($order)->paginate($page_config);

        foreach($data as $key=>$value){
            $withdrawalInfo = WithdrawalInfo::field('alipay_card,alipay_name,phone,identity_card,bank,bank_branch,bank_number')->where('user_id','=',$value['user_id'])->find();
            $userInfo = User::field('u_number,nickname')->where('user_id','=',$value['user_id'])->find();
            $data[$key]['u_id'] = $userInfo['u_number']?$userInfo['u_number']:'233';
            $data[$key]['nickname'] = $userInfo['nickname']?$userInfo['nickname']:'无名';
            $data[$key]['alipay_card'] = $withdrawalInfo['alipay_card'];
            $data[$key]['alipay_name'] = $withdrawalInfo['alipay_name'];
            $data[$key]['phone'] = $withdrawalInfo['phone'];
            $data[$key]['identity_card'] = $withdrawalInfo['identity_card'];
            $data[$key]['bank'] = $withdrawalInfo['bank']?$withdrawalInfo['bank']:'暂无';
            $data[$key]['bank_branch'] = $withdrawalInfo['bank_branch']?$withdrawalInfo['bank_branch']:'暂无';
            $data[$key]['bank_number'] = $withdrawalInfo['bank_number']?$withdrawalInfo['bank_number']:'暂无';
        }
        return $data;
    }

    /**
     * Notes: 提现总额
     * User: 王俊成
     * Date: 2018/10/24
     * Time: 16:12
     * @return array
     */
    public function countData(){
        $startTime = input('get.start_time');
        $endTime = input('get.end_time');
        $applyType = input('get.apply_type');
        $status = input('get.status');
        $u_id = input('get.u_id');
        $map = [];

        if(!empty($u_id)){

            $user_id = User::where('u_number','=',$u_id)->value('user_id');
            $map[] = ['user_id','=',$user_id];
        }

        if($applyType != 0){
            $map[] = ['type','=',$applyType];
        }
        if(!empty($startTime) && !empty($endTime)){
            $startTime = strtotime($startTime);
            $endTime = strtotime($endTime);
            if($startTime <= $endTime)
                $map[] = ['create_time','between',[$startTime,$endTime]];
            else
                $map[] = ['create_time','between',[$endTime,$startTime]];
        }
        else if(!empty($startTime)){
            $startTime = strtotime($startTime);
            $map[] = ['create_time','>=',$startTime];
        }
        else if(!empty($endTime)){
            $endTime = strtotime($endTime);
            $map[] = ['create_time','<=',$endTime];
        }
        $map[] = ['status','=',$status];
        $countData = $this->where($map)->sum('apply_amount');
        if(empty($countData)) $countData = 0;

        return ['code'=>100,'data'=>$countData];
    }

    /**
     * Notes: 获取用户信息
     * User: 王俊成
     * Date: 2018/10/26
     * Time: 18:39
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getUserInfo(){

        $user_id = input('get.user_id');

        $userInfo = User::with('userInfo')->where('user_id',$user_id)->findOrFail();
        if($userInfo){
            if($userInfo['user_info']){
                $userInfo = array_merge($userInfo->toArray(),$userInfo['user_info']->toArray());
            }
        }
        //return json(['code'=>$userInfo]);
        //收到的礼物分页
        $page_config = array(
            'page' => input('get.page', 1),
            'list_rows' => input('get.limit', 5),
            'query'=>[
                'user_id' => $user_id
            ]
        );

        $type = input('type',2);
        //送出的礼物分页
        $send_page_config = array(
            'page' => input('get.page', 1),
            'list_rows' => input('get.limit', 5),
            'query'=>[
                'user_id' => $user_id,
                'type' => 1,  //作为送出的礼物唯一标志
            ]
        );
        //return $userInfo;
        if($userInfo){
            if(!isset($userInfo['pic']))
                $userInfo['pic'] = config('site_url').'/static/admin/images/nickPic.png';

//            $charmSum = GiftRecord::where('receive_user_id','=',$user_id)->sum('charm_value');
//            $wealthSum = GiftRecord::where('receive_user_id','=',$user_id)->sum('charm_value');
            $charmSum = 0;
            $wealthSum = 0;
            $userInfo['charm_level'] = checkRank($charmSum,'charm')['rank'];
            $userInfo['wealth_level'] = checkRank($wealthSum,'wealth')['rank'];
            // $familyMember = FamilyMembers::where('user_id',$user_id)->find();
//            if($familyMember){
//                if($familyMember['check'] == 1)
//                    $userInfo['is_heads'] = '是';
//                else
//                    $userInfo['is_heads'] = '否';
//                $userInfo['family_name'] = Family::where('id',$familyMember['family_id'])->value('f_name');
//            }
//            else{
//                $userInfo['is_heads'] = '否';
//                $userInfo['family_name'] = '暂无！';
//            }
            $userInfo['follow_num'] = SatinFollow::where('user_id',$user_id)->count();
            $userInfo['fans_num'] = SatinFollow::where('follow_user_id',$user_id)->count();
            $alipay = WithdrawalInfo::where('user_id',$user_id)->find();
            if($alipay){
                $userInfo['alipay'] = $alipay['alipay_card'];
                $userInfo['alipay_name'] = $alipay['alipay_name'];
            }
            else{
                $userInfo['alipay'] = '暂无绑定';
                $userInfo['alipay_name'] = '暂无绑定';
            }
            $recharge = Recharge::where([['user_id','=',$user_id],['status','=',2]])->fieldRaw('SUM(amount) as allmoney,SUM(diamonds) as alldiamonds')->find();
            if($recharge){
                $userInfo['recharge_money'] = $recharge['allmoney'];
                $userInfo['recharge_diamonds'] = $recharge['alldiamonds'];
            }
            else{
                $userInfo['recharge_money'] = 0;
                $userInfo['recharge_diamonds'] = 0;
            }
            //礼物累计提现金额
            $withdrawalAmonut = Withdrawal::where([['user_id','=',$user_id],['status','=',3],['type','=',1]])->sum('apply_amount');
            //推荐累计提现金额
            $introduceAmount = Withdrawal::where([['user_id','=',$user_id],['status','=',3],['type','=',2]])->sum('apply_amount');
            if(!$withdrawalAmonut)
                $withdrawalAmonut = 0;
            if(!$introduceAmount)
                $introduceAmount = 0;
            $userInfo['Withdrawal_amount'] = $withdrawalAmonut;
            $userInfo['introduce_amount'] = $introduceAmount;
            //累计兑换的RMB/钻石
            $exchange = Exchange::where('user_id',$user_id)->fieldRaw('SUM(exchange_money) as allmoney,SUM(exchange_diamonds) as alldiamonds')->find();
            if($exchange){
                $userInfo['exchange_money'] = $exchange['allmoney'];
                $userInfo['exchange_diamonds'] = $exchange['alldiamonds'];
            }
            else{
                $userInfo['exchange_money'] = 0;
                $userInfo['exchange_diamonds'] = 0;
            }
            //累计消费的钻石
            if($userInfo['recharge_diamonds'] == 0)
                $userInfo['cost_diamonds'] = 0;
            else
                $userInfo['cost_diamonds'] = $userInfo['recharge_diamonds'] - $userInfo['diamonds'];
            //收到的礼物
//            $giftData = GiftRecord::where('receive_user_id',$user_id)->fieldRaw('SUM(num) as allnum,SUM(gold_price) as allgold,SUM(gift_price) as alldiamonds,gift_type')->group('gift_type')->paginate($page_config);
            $giftData = GiftRecord::where('receive_user_id',$user_id)->fieldRaw('SUM(num) as allnum,SUM(gift_price) as alldiamonds,gift_type')->group('gift_type')->paginate($page_config);
            if($giftData){
                foreach($giftData as $key => $value){
                    $value['gift_name'] = get_gift_name($value['gift_type']);
                    $value['gift_pic'] = get_gift_pic($value['gift_type']);
                    $giftData[$key] = $value;
                }
            }

            //送出的礼物
//            $sendGiftData = GiftRecord::where('send_user_id',$user_id)->fieldRaw('SUM(num) as allnum,SUM(gold_price) as allgold,SUM(gift_price) as alldiamonds,gift_type')->group('gift_type')->paginate($send_page_config);
            $sendGiftData = GiftRecord::where('send_user_id',$user_id)->fieldRaw('SUM(num) as allnum,SUM(gift_price) as alldiamonds,gift_type')->group('gift_type')->paginate($send_page_config);
            foreach($sendGiftData as $key => $value){
                $value['gift_name'] = get_gift_name($value['gift_type']);
                $value['gift_pic'] = get_gift_pic($value['gift_type']);
                $value['type'] = $type;
                $sendGiftData[$key] = $value;

            }

          // halt($sendGiftData);
            return ['userInfo' => $userInfo,'giftData' => $giftData,'sendGiftData'=>$sendGiftData];
        }
    }

    /**
     * Notes: 处理提现申请
     * User: 王俊成
     * Date: 2018/10/25
     * Time: 16:21
     * @return array
     */
    public function dealwithApply(){
        $id = input('post.id');
        $dealType = input('post.dealType');
        if(!empty($id) && !empty($dealType)){
            $applyInfo = $this->where('id','=',$id)->field('status,type,apply_amount,user_id')->find();
            if($applyInfo){//该申请单存在
                //获取原始数据（把获取器产生的过滤数据转换为原始数据）
                $applyInfo = $applyInfo->getData();
                if($applyInfo['status'] != 1)
                    return ['resultCode'=>-1000,'resultData'=>null,'resultDes'=>'此申请已经审核完成了，请勿重复审核！'];
                else{
                    $remark = input('post.remark');
                    $data = [];
                    if($dealType == 1){
                        $msg = '拒绝';
                        $data = [
                            'status'=>2,
                            'remark'=>$remark,
                            'update_time'=>time()
                        ];
                    }
                    else if($dealType == 2){
                        $msg = '同意';
                        $data = ['status'=>3,'update_time'=>time()];
                    }
                    $this->startTrans();
                    $res = $this->save($data,['id'=>$id]);
                    if($res !== false){
                        if($dealType == 2 && $applyInfo['type'] == 1){
                            //帅吴
                            $rs = RoomProfit::where(['user_id'=>$applyInfo['user_id']])->setDec('money',$applyInfo['apply_amount']);
//                            $user = User::get($applyInfo['user_id']);
//                            $user->money = ['dec',$applyInfo['apply_amount']];
//                            $rs = $user->save();
                        }
                        else if($dealType == 2 && $applyInfo['type'] == 2){
                            return ['resultCode'=>-1100,'resultData'=>null,'resultDes'=>'操作失败233！'];
                            $user = User::get($applyInfo['user_id']);
                            $user->introduce_money = ['dec',$applyInfo['apply_amount']];
                            $rs = $user->save();
                        }
                        else
                            $rs = true;
                        if($rs !== false){
                            $logMessage = session('admin_name').$msg.'了用户'.get_user_name($applyInfo['user_id']).'的提现申请';
                            AdminLog::create([
                                'log'=>$logMessage
                            ]);
                            $this->commit();
                            return ['resultCode'=>100,'resultData'=>null,'resultDes'=>'操作成功！'];
                        }
                        else{
                            $this->rollback();
                            return ['resultCode'=>-1100,'resultData'=>null,'resultDes'=>'操作失败！'];
                        }
                    }
                    else{
                        $this->rollback();
                        return ['resultCode'=>-1100,'resultData'=>null,'resultDes'=>'操作失败！'];
                    }
                }
            }
            else//该申请单不存在
                return ['resultCode'=>-1100,'resultData'=>null,'resultDes'=>'操作失败！'];
        }
        else
            return ['resultCode'=>-200,'resultData'=>null,'resultDes'=>'必要参数缺失！'];

    }

    /**
     * Notes: 批量处理提现申请
     * User: 王俊成
     * Date: 2018/10/27
     * Time: 17:14
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function batchDealwithApply(){
        $idArr = input('post.idArr');
        $dealType = input('post.dealType');
        $remark = input('post.remark');
        if(!empty($idArr) && !empty($dealType)){
            if($dealType == 1){
                $msg = '拒绝';
                $data = [
                    'status'=>2,
                    'remark'=>$remark,
                    'update_time'=>time()
                ];
            }
            else if($dealType == 2){
                $msg = '同意';
                $data = ['status'=>3,'update_time'=>time()];
            }
            //开启多表事务
            Db::connect('db_data')->startTrans();
            foreach($idArr as $value){
                $applyInfo = $this->where('id',$value)->field('status,type,apply_amount,user_id')->find();
                if($applyInfo){//申请单存在
                    //获取原始数据（把获取器产生的过滤数据转换为原始数据）
                    $applyInfo = $applyInfo->getData();
                    if($applyInfo['status'] != 1){
                        $res = true;
                        continue;
                    }
                    $applyRes = Db::connect('db_data')->name('withdrawal_apply')->where('id',$value)->update($data);
                    if($applyRes !== false){
                        if($dealType == 2 && $applyInfo['type'] == 1)
                            $decMoneyRes = Db::connect('db_data')->name('room_profit')->where(['user_id'=>$applyInfo['user_id']])->setDec('money',$applyInfo['apply_amount']);
                        else if($dealType == 2 && $applyInfo['type'] == 2)
                            $decMoneyRes = Db::connect('db_data')->name('users')->where('id',$applyInfo['user_id'])->setDec('introduce_money',$applyInfo['apply_amount']);
                        else
                            $decMoneyRes = true;
                        if($decMoneyRes !== false){
                            $logMessage = session('admin_name').$msg.'了用户'.get_user_name($applyInfo['user_id']).'的提现申请';
                            $logRes = Db::connect('db_data')->name('admin_log')->insert(['log'=>$logMessage,'create_time'=>time()]);
                            if($logRes !== false)
                                $res = true;
                            else{
                                $res = false;
                                break;
                            }
                        }
                        else{
                            $res = false;
                            break;
                        }
                    }
                    else{
                        $res = false;
                        break;
                    }
                }
                else{//有申请单不存在
                    $res = false;
                    break;
                }
            }
            if($res){
                Db::connect('db_data')->commit();
                return ['resultCode'=>100,'resultData'=>$applyInfo,'resultDes'=>'操作成功！'];
            }
            else{
                Db::connect('db_data')->rollback();
                return ['resultCode'=>-1000,'resultData'=>null,'resultDes'=>'操作失败！'];
            }
        }
        else
            return ['resultCode'=>-200,'resultData'=>null,'resultDes'=>'必要参数缺失！'];
    }

    /**
     * Notes: 提现数据导出
     * User: 王俊成
     * Date: 2018/10/29
     * Time: 16:25
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function withdrawalDataExport(){
        // $keyWords = input('get.keyWords');
        $u_id = input('get.u_id');
        $startTime = input('get.start_time');
        $endTime = input('get.end_time');
        $applyType = input('get.apply_type');
        $status = input('get.status');
        $cheques = input('get.cheques');
        $map = [];
        if(!empty($u_id))
            $map[] = ['Users.u_id','=',$u_id];
        if($applyType != 0)
            $map[] = ['withdrawalApply.type','=',$applyType];
        if(!empty($status))
            $map[] = ['withdrawalApply.status','=',$status];
        if(!empty( $cheques))
            $map[] = ['withdrawalApply.cheques','=',$cheques];
        if(!empty($startTime) && !empty($endTime)){
            $startTime = strtotime($startTime);
            $endTime = strtotime($endTime);
            if($startTime <= $endTime)
                $map[] = ['withdrawalApply.create_time','between',[$startTime,$endTime]];
            else
                $map[] = ['withdrawalApply.create_time','between',[$endTime,$startTime]];
        }
        else if(!empty($startTime)){
            $startTime = strtotime($startTime);
            $map[] = ['withdrawalApply.create_time','>=',$startTime];
        }
        else if(!empty($endTime)){
            $endTime = strtotime($endTime);
            $map[] = ['withdrawalApply.create_time','<=',$endTime];
        }


        $data = $this->view('Users','u_id,nickname')->view('withdrawalInfo', 'alipay_card,alipay_name', 'withdrawalInfo.user_id=Users.id')
            ->view('withdrawalApply', 'id,apply_amount,cheques,type,create_time', 'withdrawalApply.user_id=Users.id')
            ->where($map)->order(['withdrawalApply.create_time'=>'desc'])->select();
        $allMoney = 0;
      //  halt($data);
        if($data){
            foreach($data as $key => $value){
                $value['nickname'] = filterEmoji($value['nickname']);
                $value['apply_amount'] = intval($value['apply_amount']);
                $value['cheques'] = get_cheques_type($value['cheques']);
//                $value['bank_number'] = '`'.$value['bank_number'];
//                $value['no'] = ' ' . date('Ymd') . sprintf("%06d",$value['id']);
                $allMoney += $value['apply_amount'];
                $data[$key] = $value;
            }
        }
//        halt($data);
        if($status == 0)
            $fileName = '提现数据（全部）-'.date('Y-m-d');
        else if($status == 1)
            $fileName = '提现数据（申请中）-'.date('Y-m-d');
        else if($status == 2)
            $fileName = '提现数据（拒绝）-'.date('Y-m-d');
        else
            $fileName = '提现数据（成功）-'.date('Y-m-d');
        $remarkData = ['日期：'.date('Y-m-d'),'总金额：'.$allMoney,'总笔数：'.count($data)];
        $cellTitle = [
            ['u_id','用户ID'],
            ['nickname','用户昵称'],
          //  ['no','商户流水号'],
            ['alipay_card','收款人支付宝'],
            ['alipay_name','收款人姓名'],
            ['apply_amount','付款金额（元）'],
            ['cheques','打款方式'],
//            ['bank','银行名称'],
//            ['bank_branch','支行名称'],
//            ['bank_number','银行卡号'],
            ['type','付款理由'],
            ['create_time','申请时间']
        ];
        $excelObj = new \app\common\api\Excel();
        $excelObj->exportExcel($fileName,$remarkData,$cellTitle,$data);
//        \app\common\api\Excel::exportExcel($xlsName,$remarkData,$xlsCell,$data);//当该方法为静态方法时可以这样调用
    }


    //单个用户的提现记录
    public function withdrawDetail()
    {

        $user_id = input('user_id');
        $userInfo = User::where('user_id','eq',$user_id)->field('u_number as u_id,nickname')->find();

        $page_config = [

            'page'=>input('page',1),
            'list_rows'=>input('limit',25),
            'query'=>[
                'user_id' => $user_id,
            ]
        ];

        $data = $this->where([ ['user_id','eq',$user_id],['status','eq',3],['type','eq',1] ])->order('created_at DESC')->paginate($page_config);

        foreach($data as $k => $v){

            $data[$k]['u_id'] = $userInfo['u_id'];
            $data[$k]['nickname'] = $userInfo['nickname'];

        }
        return $data;

    }

    //某个用户收到的礼物详情
    public function receiveGiftDetail()
    {
        $user_id = input('user_id');
        $pageConfig = [
            'list_rows' => 50,
            'page' => input('get.page',1),
            'query' => [
                'user_id' => $user_id
            ]
        ];
        $data = GiftRecord::where('receive_user_id',$user_id)->order('created_at DESC')->paginate($pageConfig);
        foreach($data as $key => $value){
            $data[$key]['send_user_name'] = get_user_name($value['send_user_id']);
            $data[$key]['gift_name'] = get_gift_name($value['gift_type']);
            $data[$key]['gift_pic'] = get_gift_pic($value['gift_type']);
            $data[$key]['r_name'] = get_room_name($value['room_id']);
            $data[$key]['gold_total'] = $value['num'] * $value['gold_price'];
            $data[$key]['diamonds_total'] =  $value['gift_price'];
        }
        return $data;
    }
    //某个用户送出的礼物详情
    public function sendGiftDetail()
    {
        $user_id = input('user_id');
        $pageConfig = [
            'list_rows' => 50,
            'page' => input('get.page',1),
            'query' => [
                'user_id' => $user_id
            ]
        ];
        $data = GiftRecord::where('send_user_id',$user_id)->order('created_at DESC')->paginate($pageConfig);
        foreach($data as $key => $value){
            $data[$key]['receive_user_name'] = get_user_name($value['receive_user_id']);
            $data[$key]['gift_name'] = get_gift_name($value['gift_type']);
            $data[$key]['gift_pic'] = get_gift_pic($value['gift_type']);
            $data[$key]['r_name'] = get_room_name($value['room_id']);
            $data[$key]['gold_total'] = $value['num'] * $value['gold_price'];
            $data[$key]['diamonds_total'] =  $value['gift_price'];
        }
        return $data;
    }

}